package com.fingard.dsp.bank.directbank.fuiou01;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RefundState;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.text.SplitHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;


/**
 * 富友对账单获取
 *
 * @author latte
 * @date 2019/5/27
 */
public class FUIOU01Statement extends FUIOU01Base implements IStatement {
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();
        //获取充值对账单
        String[] rechargeRespHeader = getRechargeStatement(p_reqQrySttm, retAts);
        String rechargeTotalNum = retAts.totalNum;
        WriteBankLogLn("充值对账单总笔数:" + rechargeTotalNum);
        if (rechargeTotalNum.length() == 0) {
            rechargeTotalNum = "0";
        }
        //获取代付对账单
        String[] tmpPayRespHeader = getPayStatement(p_reqQrySttm, retAts);
        String tmpPayTotalNum = retAts.totalNum;
        WriteBankLogLn("代付对账单总笔数:" + tmpPayTotalNum);
        if (tmpPayTotalNum.length() == 0) {
            tmpPayTotalNum = "0";
        }
        if (rechargeRespHeader[0].equals("-1")&&tmpPayRespHeader[0].equals("-1")) {
            String respInfo = rechargeRespHeader[1];
            if (StringHelper.isNullOrEmpty(respInfo)) {
                respInfo = tmpPayRespHeader[1];
            }
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(respInfo);
        } else {
            if (retAts.getWrittenRdCount() == 0) {
                retAts.writeRespCode("0");
                String respInfo = rechargeRespHeader[1];
                if (StringHelper.isNullOrEmpty(respInfo)) {
                    respInfo = tmpPayRespHeader[1];
                }
                if (StringHelper.isNullOrEmpty(respInfo)) {
                    respInfo = "交易为空";
                }
                retAts.writeRespInfo(respInfo);
            }

            int totalNum = Integer.parseInt(rechargeTotalNum) + Integer.parseInt(tmpPayTotalNum);
            retAts.isWritedTotalNum(String.valueOf(totalNum));
        }
        retAts.writeEnd();
        return retAts;
    }

    private String[] getRechargeStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
        String[] respHeader = new String[]{"", ""};
        String respCode = "";
        String respInfo = "";
        retAts.totalNum = "0";
        int totalNum = 0;
        
        try {
            ActSetItem actItem = this.getBankConfig().getActSetItemByAny(p_reqQrySttm.actNum, "", "", "Statement");

            if (actItem != null) {
                // FTP服务器配置信息
                String ftpHost = getBankConfig().getMapValueByKey("ftpMapping", "ftpHost");
                int ftpPort = Integer.parseInt(getBankConfig().getMapValueByKey("ftpMapping", "ftpPort"));

                // FTP登录用户信息
                String ftpUserName = getBankConfig().getMapValueByKey("ftpMapping", "ftpUserName");
                String ftpPassword = getBankConfig().getMapValueByKey("ftpMapping", "ftpPassword");

                // 对账单文件所在目录
                String ftpPath = getBankConfig().getMapValueByKey("ftpMapping", "ftpPath");
                ftpPath = ftpPath + Format.Date8Format.format(new Date()) + "/";

                // 本地路径
                String localPath = getBankConfig().getMapValueByKey("ftpMapping", "localPath");
                String fileName = Format.Date8Format.format(new Date()) + "_" + actItem.merchantId + "_" +"recharge.txt";

                // 从FTP下载对账单
                FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);

                // 从本地文件读取对账单数据
                String filePath1 = localPath + File.separator + fileName;
                String ftpFileContent = FtpUtil.getTextFromFile(filePath1, getCharset());
                if (ftpFileContent.equals("")) {
                    respCode = "-1";
                    respInfo = "读取对账单文件失败!";
                }
                // 返回对账单文件数据
                WriteBankLogStep3(ftpFileContent);
                // 解析富友对账单
                String[] totalLine = ftpFileContent.split("\r\n");
                if (totalLine.length > 1) {
                    respCode = "0";
                    respInfo = "";

                    String tmpStrRet = ftpFileContent.toString();
                    WriteBankLogLn2("充值对账单响应数据:\r\n" + tmpStrRet);

                    StringReader strReader = new StringReader(tmpStrRet);
                    BufferedReader tmpReader = new BufferedReader(strReader);
                    //业务代码|交易日期|交易流水|记账日期|记账流水|交易金额(单位:分)
                    String[] columns = new String[]{"业务代码", "交易日期", "交易流水", "记账日期", "记账流水", "交易金额"};
                    String line = "";
                    while ((line = tmpReader.readLine()) != null) {
                        // 每行明细内容
                        String eachline = line.trim();
                        if (eachline == null) {
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo("本日或本月无收支");
                            break;
                        } else {
                            if (eachline.equals("")) {
                                continue;
                            }
                            String[] values = eachline.split("\\|");
                            if (columns.length == values.length) {
                                HashMap<String, String> mapKV = SplitHelper.splitAsValueMap(columns, values);
                                RetAtsStatementDetail retDetail = new RetAtsStatementDetail();
                                totalNum++;
                                if (mapKV.containsKey("业务代码")) {
                                    retDetail.busType = mapKV.get("业务代码").trim();
                                }
                                if (mapKV.containsKey("交易日期")) {
                                    retDetail.busTime = mapKV.get("交易日期").trim();
                                }
                                if (mapKV.containsKey("交易流水")) {
                                    retDetail.askNumber = mapKV.get("交易流水").trim();
                                }
                                if (mapKV.containsKey("记账日期")) {
                                    retDetail.postingDate = mapKV.get("记账日期").trim() + "000000";
                                }

                                if (mapKV.containsKey("交易金额")) {
                                    retDetail.amount = mapKV.get("交易金额").trim();
                                }
                                retDetail.transState = TransState.Success;
                                retDetail.refundState = RefundState.Exception;
                                retAts.writeRetDetail(retDetail);
                            } else {
                                break;
                            }
                        }
                    }
                } else {
                    respCode = "-1";
                    respInfo = "返回结果不符合预期!";
                }
            } else {
                respHeader[0] = "-1";
                respHeader[1] = "未找到账号[" + p_reqQrySttm.actNum + "]商户配置信息";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            respCode = "-1";
            respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.totalNum = String.valueOf(totalNum);
        respHeader[0] = respCode;
        respHeader[1] = respInfo;
        return respHeader;
    }

    private String[] getPayStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
        String[] respHeader = new String[]{"", ""};
        String respCode = "";
        String respInfo = "";
        retAts.totalNum = "0";
        int totalNum = 0;

        try {
            ActSetItem actItem = this.getBankConfig().getActSetItemByAny(p_reqQrySttm.actNum, "", "", "Statement");

            if (actItem != null) {
                // FTP服务器配置信息
                String ftpHost = getBankConfig().getMapValueByKey("ftpMapping", "ftpHost");
                int ftpPort = Integer.parseInt(getBankConfig().getMapValueByKey("ftpMapping", "ftpPort"));

                // FTP登录用户信息
                String ftpUserName = getBankConfig().getMapValueByKey("ftpMapping", "ftpUserName");
                String ftpPassword = getBankConfig().getMapValueByKey("ftpMapping", "ftpPassword");

                // 对账单文件所在目录
                String ftpPath = getBankConfig().getMapValueByKey("ftpMapping", "ftpPath");
                ftpPath = ftpPath + Format.Date8Format.format(new Date()) + "/";

                // 本地路径
                String localPath = getBankConfig().getMapValueByKey("ftpMapping", "localPath");
                String fileName = actItem.merchantId + "_" + Format.Date8Format.format(new Date()) + ".txt";

                // 从FTP下载对账单
                FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);

                // 从本地文件读取对账单数据
                String filePath2 = localPath + File.separator + fileName;
                String ftpFileContent = FtpUtil.getTextFromFile(filePath2, getCharset());
                if (ftpFileContent.equals("")) {
                    respCode = "-1";
                    respInfo = "读取对账单文件失败!";
                }
                // 返回对账单文件数据
                WriteBankLogStep3(ftpFileContent);
                // 解析富友对账单
                //业务代码|交易来源|交易流水号|源交易流水号|富友帐务流水号|文件明细号|交易提交时间|商户复核时间|交易发送时间|
                // 交易类型|文件名|交易金额|交易手续费|户名|扣款账号|卡属性|发卡机构|收款账号|注释|企业流水号|备注|手机号
                String[] totalLine = ftpFileContent.split("\r\n");
                for(int i=1;i<totalLine.length;i++){
                    RetAtsStatementDetail retDetail = new RetAtsStatementDetail();
                    String[] values = totalLine[i].split("\\|");
                    totalNum++;
                    if (StringHelper.hasAnyChar(values[9])) {
                        retDetail.busType = values[9];
                    }
                    //交易提交时间
                    if (StringHelper.hasAnyChar(values[6])) {
                        retDetail.busTime = values[6];//mapKV.get("交易日期").trim();
                    }
                    if (StringHelper.hasAnyChar(values[2])) {
                        retDetail.askNumber =values[2]; //mapKV.get("交易流水").trim();
                    }
                    //交易发送时间
                    if (StringHelper.hasAnyChar(values[8])) {
                        retDetail.postingDate =values[8];//mapKV.get("记账日期").trim() + "000000";
                    }
                    //金额要不要转换
                    if (StringHelper.hasAnyChar(values[3])) {
                        if (StringHelper.hasAnyChar(values[11])) {
                            retDetail.amount = StringHelper.amountDivide100(values[11]);
                        }
                    }else{
                        if (StringHelper.hasAnyChar(values[11])) {
                            retDetail.amount = "-" + StringHelper.amountDivide100(values[11]);
                        }
                    }
                    retDetail.transState = TransState.Success;
                    retDetail.refundState = RefundState.Exception;
                    retAts.writeRetDetail(retDetail);
                }

            } else {
                respHeader[0] = "-1";
                respHeader[1] = "未找到账号[" + p_reqQrySttm.actNum + "]商户配置信息";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            respCode = "-1";
            respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.totalNum = String.valueOf(totalNum);
        respHeader[0] = respCode;
        return respHeader;
    }
}
